<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="请输入用户名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.role" placeholder="请选择角色" clearable class="filter-item" style="width: 150px" @change="handleFilter">
        <el-option v-for="item in roleOptions" :key="item.key" :label="item.display_name" :value="item.display_name" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button type="primary" @click="handleAdd">新建用户</el-button>
    </div>
    <el-table v-loading="listLoading" :data="modelList" border style="width: 100%;margin-top:30px;" @sort-change="sortChange">
      <el-table-column label="序号" prop="id" sortable="custom" align="center" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="140"/>
      <el-table-column prop="role" label="角色" width="180"/>
      <el-table-column prop="address" label="地址"/>
      <el-table-column label="添加日期" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.datetime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述"/>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'修改用户':'新建用户'">
      <el-form ref="dataForm" :model="model" :rules="rules" label-width="80px" label-position="left">
        <el-form-item label="用户名称" prop="name">
          <el-input v-model="model.name" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="model.role" class="filter-item" placeholder="请选择角色类型">
            <el-option v-for="item in roleOptions" :key="item.key" :label="item.display_name" :value="item.display_name" />
          </el-select>
        </el-form-item>
        <el-form-item label="添加时间" prop="datetime">
          <el-date-picker v-model="model.datetime" type="datetime" placeholder="选择日期" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="model.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="model.description"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="dialogType==='new'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination' // 基于el-pagination的分页组件
import { parseTime, deepClone } from '@/utils'
import { getModelList, addModel, updateModel, deleteModel } from '@/api/user/user.js'
const defaultModel = {
  id: undefined,
  datetime: new Date(),
  name: '',
  role: '管理员',
  address: '',
  description: ''
}
const roleOptions = [
  { key: '1', display_name: '超级管理员' },
  { key: '2', display_name: '管理员' },
  { key: '3', display_name: '普通用户' }
]
export default {
  name: 'UserTable',
  components: { Pagination },
  // 自定义过滤器，可被用于一些常见的文本格式化
  filters: {
    parseTime
  },
  data() {
    return {
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        name: undefined,
        role: undefined,
        sort: '+id'
      },
      model: Object.assign({}, defaultModel),
      dialogVisible: false,
      dialogType: 'new',
      modelList: [],
      roleOptions,
      rules: {
        name: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
        role: [{ required: true, message: '必填项不能为空', trigger: 'change' }],
        datetime: [{ type: 'date', required: true, message: '必填项不能为空', trigger: 'change' }],
        address: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getModelList(this.listQuery).then(response => {
        this.modelList = response.data.items
        this.total = response.data.total
        // 这里只是为了模拟请求的时间
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    handleAdd() {
      this.model = Object.assign({}, defaultModel)
      this.dialogType = 'new'
      this.dialogVisible = true
      // this.$nextTick(callback)，当dom发生变化，更新后执行的回调。
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleEdit(index, row) {
      // console.log(index, row)
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.model = Object.assign({}, row)
      this.model.datetime = new Date(this.model.datetime)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(index, row) {
      // console.log(index, row)
      this.$confirm('确定删除?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await deleteModel(row.key)
        this.modelList.splice(index, 1)
        this.total = this.total - 1
        this.$message({
          type: 'success',
          message: res.message
        })
      })
        .catch(err => { console.error(err) })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.model.id = parseInt(this.modelList.length) + 1 // mock a id
          addModel(this.model).then(res => {
            this.modelList.unshift(this.model)
            this.dialogVisible = false
            this.$message({
              message: res.message,
              type: 'success'
            })
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 这个的作用是修改完user点击确定修改才体现在视图上
          const tempData = deepClone(this.model)
          tempData.datetime = +new Date(tempData.datetime) // 将 Thu Nov 30 2017 16:41:05 GMT+0800 (CST) 变为 1512031311464
          updateModel(tempData).then(res => {
            for (const v of this.modelList) {
              if (v.id === this.model.id) {
                const index = this.modelList.indexOf(v)
                this.modelList.splice(index, 1, this.model)
                break
              }
            }
            this.dialogVisible = false
            this.$message({
              message: res.message,
              type: 'success'
            })
          })
        }
      })
    }
  }
}
</script>
